// 定义价格清理工具函数（对应Python中的clean_arabic_price/clean_canadian_price/clean_mexican_price）
// 注：需根据实际业务逻辑补充具体实现，此处保留函数结构以匹配原Python逻辑
import { normalizePrice } from "./utils";

/** 清理阿拉伯语价格（移除非数字字符、处理本地化格式） */
function cleanArabicPrice(priceStr: string): string {
  /** 
  清理阿拉伯语价格字符串，支持阿拉伯语数字和标点符号。
  示例输入：'23,628.80 ريال'
  输出：'23628.80'
  */
  if (!priceStr) {
    return "";
  }

  // 替换阿拉伯语标点符号
  let cleaned = priceStr
    .replace("،", ",") // 阿拉伯语逗号替换为英文逗号
    .replace("٫", "."); // 阿拉伯语小数点替换为英文小数点

  // 移除非数字字符（保留数字、逗号和小数点）
  cleaned = cleaned.replace(/[^\d.,]/g, "");

  // 移除千位分隔符逗号
  cleaned = cleaned.replace(/,/g, "");

  // 返回标准化后的价格
  return cleaned;
}

/**
 * 清理加拿大价格字符串
 * 示例输入: "$3,299.00", "CAD$ 1,499.99"
 * 输出: "3299.00", "1499.99"
 */
function cleanCanadianPrice(priceText: string): string {
  if (!priceText) {
    return "";
  }

  // 移除货币符号和空格
  priceText = priceText.trim().replace(/CAD\$|\$|\s/g, "");

  // 处理加拿大格式的数字（逗号作为千位分隔符）
  if (priceText.includes(",") && priceText.includes(".")) {
    // 格式: "3,299.00" → "3299.00"
    priceText = priceText.replace(/,/g, "");
  } else if (priceText.includes(",")) {
    // 格式: "1,299" → "1299"
    priceText = priceText.replace(/,/g, "");
  }

  // 验证价格格式
  if (/^\d+(\.\d{1,2})?$/.test(priceText)) {
    return priceText;
  }

  return "";
}

/**
 * 清理墨西哥市场价格的整数部分，移除多余的小数点或其他符号
 * @param priceText 原始价格文本
 * @return 清理后的价格字符串
 */
function cleanMexicanPrice(priceText: string): string {
  if (!priceText) {
    return "";
  }
  // 移除所有非数字字符（保留数字和小数点）
  let cleaned = priceText.replace(/[^\d.]/g, "");
  // 如果有多余的小数点，只保留第一个
  const parts = cleaned.split(".");
  if (parts.length > 1) {
    // 检查第二部分是否为数字，若是则保留小数点和该部分，否则只保留第一部分
    cleaned = parts[0] + (/\d+/.test(parts[1]) ? "." + parts[1] : "");
  }
  return cleaned;
}

/**
 * 清理德国市场价格的整数部分，移除多余的小数点或其他符号
 * @param priceText 原始价格文本
 * @return 清理后的价格字符串
 */
function cleanDeuPrice(priceText: string): string {
  if (!priceText) {
    return "";
  }
  // 1. 移除所有非数字、非.非,的字符（如€、空格等）
  const cleaned = priceText.replace(/[^\d.,]/g, "");
  // 2. 处理德国格式：移除千位分隔符.，替换小数点,为.
  const standardFormat = cleaned.replace(/\./g, "").replace(",", ".");
  // 3. 转换为数字
  return `${parseFloat(standardFormat)}`;
}

/**
 * 清理法国市场价格的整数部分，移除多余的小数点或其他符号
 * @param priceText 原始价格文本
 * @return 清理后的价格字符串
 */
function cleanFraPrice(priceText: string): string {
  if (!priceText) {
    return "";
  }
  return normalizePrice(priceText, "FRA");
}

function cleanUsPriceString(s: string): string {
  if (!s) {
    return "";
  }

  // 1. 删除隐藏控制字符
  s = s.replace(/[\u200B-\u200F\u202A-\u202E]/g, "");

  // 2. 移除常见价格前缀
  s = s.replace(/Typical\s*price:/gi, "");

  // 3. 移除货币符号和千位分隔符
  s = s.replace(/[$,]/g, "").trim();

  // 4. 统一空白并去除前后空格
  s = s.replace(/\s+/g, " ").trim();

  // 5. 处理小数点（修正核心：分割为两部分保留小数）
  const parts = s.split("."); // 去掉分割数量限制，默认分割所有
  if (parts.length > 1) {
    // 保留第一个小数点，后续部分只保留数字
    s =
      parts[0].replace(/[^\d]/g, "") +
      "." +
      parts.slice(1).join("").replace(/[^\d]/g, "");
  } else {
    // 没有小数点时只保留数字
    s = s.replace(/[^\d]/g, "");
  }

  // 处理特殊情况：如果结果为空或只有小数点
  if (s === "" || s === ".") {
    return "";
  }

  return s;
}
function extractUsPrice(priceContainer: HTMLElement): string {
  /**
   * 提取商品的典型价格（Typical price），优先匹配 basisPrice 容器中的内容，
   * 如果未找到，则回退到提取整数部分和小数部分的逻辑。
   * @param priceContainer - 解析后的HTML文档对象
   * @returns 典型价格字符串（如 "15.99"），如果未找到则返回空字符串
   */

  // 查找带有 'basisPrice' 类的容器
  const basisPriceContainer = priceContainer.querySelector("span.basisPrice");
  if (basisPriceContainer) {
    // 查找带有 'a-offscreen' 类的典型价格标签
    const offscreenPrice =
      basisPriceContainer.querySelector("span.a-offscreen");
    if (offscreenPrice) {
      let text = offscreenPrice.textContent?.trim() || "";
      text = cleanUsPriceString(text).replace("Typical price:", "").trim();
      return text;
    }

    // 如果没有 'a-offscreen'，尝试查找 'aria-hidden="true"' 的标签
    const hiddenPrice = basisPriceContainer.querySelector(
      'span[aria-hidden="true"]'
    );
    if (hiddenPrice) {
      const text = hiddenPrice.textContent?.trim() || "";
      return cleanUsPriceString(text);
    }
  }

  // 如果未找到典型价格，回退到提取整数部分和小数部分的逻辑
  const wholeElement = priceContainer.querySelector("span.a-price-whole");
  const fractionElement = priceContainer.querySelector("span.a-price-fraction");

  if (wholeElement) {
    // 提取整数部分文本，并移除所有非数字字符
    const wholeText = (wholeElement.textContent?.trim() || "").replace(
      /\D/g,
      ""
    );
    // 提取小数部分，默认为 "00"
    const fractionText = fractionElement?.textContent?.trim() || "00";
    // 拼接整数部分和小数部分
    return `${wholeText}.${fractionText}`;
  }

  return "";
}

// 活动价格
function getActivePrice(doc: Document): number {
  // 初始化价格为0
  let b = 0;
  // 1. 从id为"priceValue"的元素中获取价格
  let T = doc.querySelector("#priceValue");
  if (T) {
    let e = T.getAttribute("value");
    e && (b = parseFloat(e)); // 提取value属性并转为浮点数
  }

  // 2. 若第一步未获取到价格，从"twister-plus-price-data-price"元素中获取
  if (0 === b) {
    let e = doc.querySelector("#twister-plus-price-data-price");
    if (e) {
      let t = e.getAttribute("value");
      t && (b = parseFloat(t)); // 提取value属性并转为浮点数
    }
  }

  // 3. 若前两步未获取到价格，从包含价格符号和金额的元素中解析
  if (0 === b) {
    let e = doc.querySelector(
      ".a-section.a-spacing-none.aok-align-center.aok-relative"
    );
    if (e) {
      // 提取价格符号（如$、€）
      let t = e.querySelector(".a-price-symbol")?.textContent?.trim() || "";
      // 提取价格数值（去除符号和非数字字符后转为浮点数）
      let r = (e.querySelector(".aok-offscreen")?.textContent?.trim() || "")
        .replace(t, "")
        .replace(/[^\d.]/g, "");
      b = parseFloat(r);
    }
  }

  return b;
}

/**
 * 提取商品价格，兼容多种地区格式（JPY、EUR、USD、DEU、GBR、CAN、MEX、SAU）
 * @param doc 浏览器DOM Document对象
 * @param marketplace 市场标识符（如 JPN、DEU、GBR、CAN、MEX、SAU）
 * @returns 标准格式的价格字符串（如 "19.99" 或 "4980"）
 */
export function getProductPrice(
  doc: Document,
  marketplace: string,
  collectPriceType: string
): string {
  // 预编译价格匹配正则（对应Python的PRICE_REGEX）
  const PRICE_REGEX =
    /([€$£¥]|Rp|R\$|R\s*|MX\$|ريال)?\s*(\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{2})?)/;

  // Step 1: 查找核心价格显示区域（对应Python的find两个div）
  const priceContainer =
    doc.getElementById("corePriceDisplay_desktop_feature_div") ||
    doc.getElementById("centerCol");
  if (!priceContainer) {
    console.debug("未找到核心价格容器");
    return "";
  }

  // Step 2: 各市场专属价格提取逻辑
  // 2.1 沙特市场（SAU）专属处理
  if (marketplace === "SAU") {
    // 优先从basisPrice容器提取
    const basisPriceContainer = priceContainer.querySelector("span.basisPrice");
    if (basisPriceContainer) {
      // 查找a-offscreen类价格
      const offscreenPrice =
        basisPriceContainer.querySelector("span.a-offscreen");
      if (offscreenPrice) {
        const fullPriceText = offscreenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanArabicPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }

      // 查找aria-hidden="true"的价格
      const hiddenPrice = basisPriceContainer.querySelector(
        'span[aria-hidden="true"]'
      );
      if (hiddenPrice) {
        const fullPriceText = hiddenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanArabicPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }
    }

    // 回退：提取整数+小数部分
    const wholeElement = priceContainer.querySelector("span.a-price-whole");
    const fractionElement = priceContainer.querySelector(
      "span.a-price-fraction"
    );
    if (wholeElement) {
      const wholeText =
        wholeElement.textContent
          ?.split("")
          .filter((char) => /\d/.test(char))
          .join("") || "";
      const fractionText = fractionElement?.textContent?.trim() || "00";
      return `${wholeText}.${fractionText}`;
    }
    return "";
  }

  // 2.2 加拿大市场（CAN）专属处理
  if (marketplace === "CAN") {
    const basisPriceContainer = priceContainer.querySelector("span.basisPrice");
    if (basisPriceContainer) {
      const offscreenPrice =
        basisPriceContainer.querySelector("span.a-offscreen");
      if (offscreenPrice) {
        const fullPriceText = offscreenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanCanadianPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }

      const hiddenPrice = basisPriceContainer.querySelector(
        'span[aria-hidden="true"]'
      );
      if (hiddenPrice) {
        const fullPriceText = hiddenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanCanadianPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }
    }

    // 回退：提取整数+小数部分
    const wholeElement = priceContainer.querySelector("span.a-price-whole");
    const fractionElement = priceContainer.querySelector(
      "span.a-price-fraction"
    );
    if (wholeElement) {
      const wholeText =
        wholeElement.textContent
          ?.split("")
          .filter((char) => /\d/.test(char))
          .join("") || "";
      const fractionText = fractionElement?.textContent?.trim() || "00";
      return `${wholeText}.${fractionText}`;
    }
    return "";
  }

  // 2.3 美国/英国市场（USA/GBR）专属处理
  if (marketplace === "USA" || marketplace === "GBR") {
    const usPrice = extractUsPrice(priceContainer);
    if (usPrice) return usPrice;
  }

  // 2.4 墨西哥市场（MEX）专属处理
  if (marketplace === "MEX") {
    const basisPriceContainer = priceContainer.querySelector("span.basisPrice");
    if (basisPriceContainer) {
      const offscreenPrice =
        basisPriceContainer.querySelector("span.a-offscreen");
      if (offscreenPrice) {
        const fullPriceText = offscreenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanMexicanPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }

      const hiddenPrice = basisPriceContainer.querySelector(
        'span[aria-hidden="true"]'
      );
      if (hiddenPrice) {
        const fullPriceText = hiddenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanMexicanPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }
    }

    // 回退：提取整数+小数部分
    const wholeElement = priceContainer.querySelector("span.a-price-whole");
    const fractionElement = priceContainer.querySelector(
      "span.a-price-fraction"
    );
    if (wholeElement) {
      const wholeText =
        wholeElement.textContent
          ?.split("")
          .filter((char) => /\d/.test(char))
          .join("") || "";
      const fractionText = fractionElement?.textContent?.trim() || "00";
      return `${wholeText}.${fractionText}`;
    }
    return "";
  }

  // 2.5 德国市场（DEU）专属处理
  if (marketplace === "DEU") {
    const basisPriceContainer = priceContainer.querySelector("span.basisPrice");
    if (basisPriceContainer) {
      const offscreenPrice =
        basisPriceContainer.querySelector("span.a-offscreen");
      if (offscreenPrice) {
        const fullPriceText = offscreenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanDeuPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }

      const hiddenPrice = basisPriceContainer.querySelector(
        'span[aria-hidden="true"]'
      );
      if (hiddenPrice) {
        const fullPriceText = hiddenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanDeuPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }
    }

    // 回退：提取整数+小数部分
    const wholeElement = priceContainer.querySelector("span.a-price-whole");
    const fractionElement = priceContainer.querySelector(
      "span.a-price-fraction"
    );
    if (wholeElement) {
      const wholeText =
        wholeElement.textContent
          ?.split("")
          .filter((char) => /\d/.test(char))
          .join("") || "";
      const fractionText = fractionElement?.textContent?.trim() || "00";
      return cleanDeuPrice(`${wholeText},${fractionText}`);
    }
    return "";
  }

  // 2.6 法国市场（FRA）专属处理
  if (marketplace === "FRA") {
    const basisPriceContainer = priceContainer.querySelector("span.basisPrice");
    if (basisPriceContainer) {
      const offscreenPrice =
        basisPriceContainer.querySelector("span.a-offscreen");
      if (offscreenPrice) {
        const fullPriceText = offscreenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanFraPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }

      const hiddenPrice = basisPriceContainer.querySelector(
        'span[aria-hidden="true"]'
      );
      if (hiddenPrice) {
        const fullPriceText = hiddenPrice.textContent?.trim() || "";
        const cleanedPrice = cleanFraPrice(fullPriceText);
        if (cleanedPrice) return cleanedPrice;
      }
    }

    const aokOffscreenPrice =
      priceContainer.querySelector("span.aok-offscreen");
    if (aokOffscreenPrice) {
      const fullPriceText = aokOffscreenPrice.textContent?.trim() || "";
      const cleanedPrice = cleanFraPrice(fullPriceText);
      if (cleanedPrice) return cleanedPrice;
    }

    // 回退：提取整数+小数部分
    const wholeElement = priceContainer.querySelector("span.a-price-whole");
    const fractionElement = priceContainer.querySelector(
      "span.a-price-fraction"
    );
    if (wholeElement) {
      const wholeText =
        wholeElement.textContent
          ?.split("")
          .filter((char) => /\d/.test(char))
          .join("") || "";
      const fractionText = fractionElement?.textContent?.trim() || "00";
      return `${wholeText}.${fractionText}`;
    }
    return "";
  }

  // Step 3: 通用逻辑 - 匹配带"Was:"的原价（aok-offscreen类）
  const pastPriceElement = Array.from(
    priceContainer.querySelectorAll("span.aok-offscreen")
  ).find(
    (el) => el.textContent?.trim().toLowerCase().includes("was:") || false
  );
  if (pastPriceElement) {
    const pastPriceText = pastPriceElement.textContent?.trim() || "";
    const match = PRICE_REGEX.exec(pastPriceText);
    if (match) {
      const [_, currency, number] = match;
      return normalizePrice(number, marketplace);
    }
  }

  // Step 4: 通用逻辑 - 匹配带删除线的原价（data-a-strike="true"）
  const pastPriceStrike = priceContainer.querySelector(
    'span.a-price[data-a-strike="true"]'
  );
  if (pastPriceStrike) {
    const offscreenPrice = pastPriceStrike.querySelector("span.a-offscreen");
    if (offscreenPrice) {
      const priceText = offscreenPrice.textContent?.trim() || "";
      const match = PRICE_REGEX.exec(priceText);
      if (match) {
        const [_, currency, number] = match;
        return normalizePrice(number, marketplace);
      }
    }
  }

  // Step 5: 通用逻辑 - 匹配当前价格（整数+小数组合）
  const currentPriceWhole = priceContainer.querySelector("span.a-price-whole");
  if (currentPriceWhole) {
    const wholeText = currentPriceWhole.textContent?.trim() || "";
    const wholeClean = normalizePrice(wholeText, marketplace);

    const priceFraction =
      currentPriceWhole.nextElementSibling as HTMLElement | null;
    if (priceFraction?.classList.contains("a-price-fraction")) {
      const fractionText = priceFraction.textContent?.trim() || "";
      if (/^\d+$/.test(fractionText)) {
        return `${wholeClean}.${fractionText}`;
      }
    }
    return wholeClean;
  }

  // Step 6: 通用逻辑 - 尝试其他选择器（多优先级兜底）
  const selectors = [
    ".a-price .a-offscreen",
    "span.a-price-whole",
    "span#priceblock_ourprice",
    "span#priceblock_dealprice",
    "#corePriceDisplay_desktop_feature_div .aok-offscreen",
  ];

  for (const selector of selectors) {
    const element = priceContainer.querySelector(selector);
    if (!element) continue;

    const text = element.textContent?.trim() || "";
    const cleanedPrice = normalizePrice(text, marketplace);
    if (cleanedPrice) return cleanedPrice;
  }

  console.debug("未匹配到任何价格");
  return "";
}
